package com.atguigu.guli.servicevod.service.impl;

import com.atguigu.guli.servicevod.service.ServiceVideoService;
import com.atguigu.servicebase.exception.Assert;
import com.atguigu.servicebase.exception.ServiceException;
import com.atguigu.servicebase.result.ResponseEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

@Slf4j
@Service
public class VideoServiceImpl implements ServiceVideoService {
    @Override
    public String uploadVideo(String courseId, String videoId, MultipartFile file) {

        try {
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();

            String path = "F:/Apache Software Foundation/Tomcat 8.5/webapps/ROOT/" + courseId;
            String fileName = videoId + ".mp4";
            // 输出的文件流保存到本地文件
            File tempFile = new File(path);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }

            // 数据缓冲
            byte[] bs = new byte[1024*1024];
            // 读取到的数据长度
            int len;
            FileOutputStream os = new FileOutputStream(path + File.separator + fileName);
            // 开始读取
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            os.close();

            String url = "http://localhost:8080" + File.separator + courseId + File.separator + fileName;
            return url;

        } catch (Exception e) {
            log.error(e.toString());
            throw new ServiceException(ResponseEnum.UPLOAD_FILE_ERROR);
        }
    }

    @Override
    public void removeVideo(String courseId, String videoId) {

        String path = "F:/Apache Software Foundation/Tomcat 8.5/webapps/ROOT/" + courseId;
        String fileName = videoId + ".mp4";
        String filePath = path + File.separator + fileName;
        File file = new File(filePath);
        if (file.exists()) {
            boolean delete = file.delete();
            Assert.notFalse(delete, ResponseEnum.DELETE_FILE_ERROR);
        }
    }
}
